import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:local_task/controller/search_controller.dart';
import 'package:local_task/controller/task_controller.dart';
import 'package:local_task/model/task_model.dart';
import 'package:local_task/pages/task_list.dart';

/// 搜索页。
class Search extends StatelessWidget {
  Search({Key? key}) : super(key: key);

  final SearchController _searchController = Get.put(SearchController());
  final TaskController _taskController = Get.put(TaskController());

  final TextEditingController _searchEditingController =
      TextEditingController(text: "");

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: TextFormField(
          controller: _searchEditingController,
          decoration: const InputDecoration(hintText: "搜索"),
          onChanged: _search,
        ),
      ),
      body: Obx(() {
        return _searchController.searchBodyWidgetObs.value;
      }),
    );
  }


  /// 执行搜索操作
  void _search(String text) {
    print("============> 搜索事件响应");

    // 从数据库获取数据。
    List<TaskEntity> tasks = _taskController.listByContentStore(text);
    if (tasks.isEmpty) {
      _searchController.searchBodyWidgetObs.value = Container(child: Center(child: Text("找不到内容"),),);
      return;
    }

    // 填充到controller。
    _taskController.taskList.removeRange(0, _taskController.taskList.length);
    // 刷新页面
    _taskController.taskList.addAll(TaskEntity.entityListToJson(tasks));
    _searchController.searchBodyWidgetObs.value = TaskList(title: '',).taskListBody();
  }

}
